package com.mk.admin.service.impl;


import com.alibaba.fastjson2.JSONObject;
import com.mk.admin.mapper.MenuMapper;
import com.mk.admin.model.ResultDto;
import com.mk.admin.model.entity.MenuAddressEntity;
import com.mk.admin.model.entity.MenuEntity;
import com.mk.admin.model.vo.MenuVo;
import com.mk.admin.service.MenuService;
import com.mk.admin.util.DateTool;
import com.mk.admin.util.JSONCopy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public ResultDto select(MenuVo vo) {
//        return ResultDto.data(menuMapper.count(JSONCopy.copy(vo, MenuEntity.class)), menuMapper.select(JSONCopy.copy(vo, MenuEntity.class)));
        if (vo.getCodes() == null) {
            MenuEntity entity = JSONCopy.copy(vo, MenuEntity.class);
            return ResultDto.data(menuMapper.count(entity), menuMapper.select(entity));
        }
        JSONObject jsonObject = new JSONObject();
        String[] codes = vo.getCodes();
        for (String code : codes) {
            MenuEntity entity = JSONCopy.copy(vo, MenuEntity.class);
            entity.setAddressCode(code);
//            这里需要查询是否只能在当前时间显示的功能
            entity.setNowDate(DateTool.format(new Date(), "yyyy-MM-dd"));
            jsonObject.put(code, menuMapper.select(entity));
        }
        return ResultDto.data(jsonObject);
    }

    @Override
    public ResultDto add(MenuVo vo) {
        MenuEntity entity = JSONCopy.copy(vo, MenuEntity.class);
        entity.setCreateTime(DateTool.format());
        return ResultDto.data(menuMapper.insert(entity));
    }

    @Override
    public ResultDto update(MenuVo vo) {
        MenuEntity entity = JSONCopy.copy(vo, MenuEntity.class);
        entity.setUpdateTime(DateTool.format());
        if ("".equals(vo.getStartDate())) {
            entity.setStartDate(null);
        }
        if ("".equals(vo.getEndDate())) {
            entity.setEndDate(null);
        }
        return ResultDto.data(menuMapper.edit(entity));
    }

    @Override
    public ResultDto delete(int id) {
        return ResultDto.data(menuMapper.deleteById(id));
    }

    @Override
    public ResultDto deleteBatchIds(List<MenuVo> list) {
        List<Integer> ids = list.stream().map(MenuVo::getId).collect(Collectors.toList());
        return ResultDto.data(menuMapper.deleteBatchIds(ids));
    }


    @Override
    public ResultDto status(int id) {
        return ResultDto.data(menuMapper.status(id));
    }


}
